import webbrowser
from zhipuai import ZhipuAI

CHATGLM_API_KEY = 'a1f4e4b57bf773c563146f6e76d4ad0b.fjRRAdqhBrK4ooDm'

class ChatglmChat:
    def __init__(self, api_key=CHATGLM_API_KEY, secret_key=''):
        self.api_key = api_key
        self.secret_key = secret_key
        self.access_token = None

    # 获取Token
    def get_token(self):
        self.access_token = self.api_key
        return self.access_token

    # 调用模型
    def do_chat(self, message):
        if not self.access_token:
            self.get_token() 

        client = ZhipuAI(api_key=self.access_token)
        response = client.chat.completions.create(
            model="glm-4-plus",
            messages=[
                {
                    "role": "user",
                    "content": message + "(注：如果用户输入有给出参考网址，那么回答时可搜索参考该网址的内容并在回答中体现)"       
                }
            ],
            stream=False
        )

        try:
            result = response.choices[0].message.content
        except (KeyError, TypeError) as e:
            print(f"Error processing chat response: {e}")
            return {"error": "响应格式不正确，请重试"}

        return result

if __name__ == '__main__':
    chat_bot = ChatglmChat()
    response = chat_bot.do_chat("你好")
    print(response)
